package top.hmtools.configClient;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 示例demo
 * @author Hybomyth
 *
 */
@RestController
public class DemoController implements ApplicationContextAware{

	private ApplicationContext applicationContext;
	
	/**
	 * 获取key的配置值
	 * @param key
	 * @return
	 */
	@RequestMapping("demo/config")
	public String demoConfig(@RequestParam("key")String key	){
		return this.getProperty(key, "none");
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext=applicationContext;
	}
	
	
	/**
	 * 根据配置键名获取配置值，如果没有，则使用缺省值。
	 * @param key
	 * @param defaultValue
	 * @return
	 */
	public String getProperty(String key,String defaultValue){
		//再尝试从系统工程配置中获取
		String result = this.applicationContext.getEnvironment().getProperty(key, defaultValue).trim();
		if(result == null || result.length()<1){
			result = defaultValue;
		}
		
		return result;
	}

}
